//
//  PointsHistory.swift
//  hello
//
//  Created by 赵康 on 2025/5/28.
//

import Vapor
import Fluent

// 积分历史记录类型
enum PointsHistoryType: Int, Codable {
  case dailyCheckIn = 0 // 每日打卡
  case share = 1 // 分享
  case milestone = 2 // 里程碑奖励
  case makeup = 3 // 补签使用
  case vipDiscount = 4 // VIP折扣
  case aiAnalysis = 5 // AI解析
}

final class PointsHistory: Model, Content, @unchecked Sendable {
  static var schema: String { SchemaEnum.pointsHistories.rawValue }
  
  @ID(key: .id)
  var id: UUID?
  
  @Parent(key: FieldKeys.user)
  var user: User
  
  @Field(key: FieldKeys.amount)
  var amount: Int // 交易金额，正数为获得，负数为消费
  
  @Field(key: FieldKeys.balance)
  var balance: Int // 交易后余额
  
  @Field(key: FieldKeys.type)
  var type: PointsHistoryType // 交易类型
  
  @Field(key: FieldKeys.description)
  var description: String // 交易描述
  
  @Field(key: FieldKeys.createdAt)
  var createdAt: Date // 交易时间
  
  init() { }
  
  init(
    id: UUID? = nil,
    userID: User.IDValue,
    amount: Int,
    balance: Int,
    type: PointsHistoryType,
    description: String,
    createdAt: Date
  ) {
    self.id = id
    self.$user.id = userID
    self.amount = amount
    self.balance = balance
    self.type = type
    self.description = description
    self.createdAt = createdAt
  }
}

extension PointsHistory {
  // 用于返回给前端的数据结构
  struct Response: Content {
    let id: UUID
    let amount: Int
    let balance: Int
    let type: PointsHistoryType
    let description: String
    let createdAt: Date
  }
}

extension PointsHistory {
  enum FieldKeys {
    static var id: FieldKey { "id" }
    static var user: FieldKey { "user_id" }
    static var amount: FieldKey { "amount" }
    static var balance: FieldKey { "balance" }
    static var type: FieldKey { "type" }
    static var description: FieldKey { "description" }
    static var createdAt: FieldKey { "created_at" }
  }
} 